// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID;
  //检查是不是新用户
  let proCount = await db.collection('userGold').where({
    openid: openid
  }).count();
  if (proCount.total != 1) {
    //如果是新用户初始化金币数并加入表
    await db.collection('userGold').add({
      data: {
        openid: openid,
        goldNum:0
      }
    });
    return{
      goldNum:0
    }
  }

  else{
    let progold= await db.collection('userGold').where({
      openid:openid
    }).get();
    return{
      goldNum: progold.data[0].goldNum
    }
  }
}